const User = require('../models/userModel');
const jwt = require('jsonwebtoken');

// 生成 JWT Token
const generateToken = (id) => {
    return jwt.sign({ id }, process.env.JWT_SECRET, {
        expiresIn: '30d',
    });
};

// 注册用户
const registerUser = async (req, res) => {
    try {
        const { username, password } = req.body;

        // 检查用户是否已存在
        const userExists = await User.findOne({ username });
        if (userExists) {
            return res.status(400).json({
                success: false,
                message: '用户名已存在'
            });
        }

        // 创建用户，只包含必要字段
        const user = await User.create({
            username,
            password,
            nickname: '',
            avatar: '',
            phone: '',
            isOnline: false
        });

        if (user) {
            res.status(201).json({
                success: true,
                data: {
                    token: generateToken(user._id),
                    userInfo: {
                        _id: user._id,
                        username: user.username,
                        nickname: user.nickname,
                        avatar: user.avatar,
                        phone: user.phone,
                        isOnline: user.isOnline,
                        lastLoginTime: user.lastLoginTime
                    }
                }
            });
        }
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message
        });
    }
};

// 用户登录
const loginUser = async (req, res) => {
    try {
        const { username, password } = req.body;

        // 查找用户
        const user = await User.findOne({ username });

        if (user && (await user.matchPassword(password))) {
            // 更新用户在线状态和最后登录时间
            user.isOnline = true;
            user.lastLoginTime = new Date();
            await user.save();

            res.json({
                success: true,
                data: {
                    token: generateToken(user._id),
                    userInfo: {
                        _id: user._id,
                        username: user.username,
                        nickname: user.nickname,
                        avatar: user.avatar,
                        phone: user.phone,
                        isOnline: user.isOnline,
                        lastLoginTime: user.lastLoginTime
                    }
                }
            });
        } else {
            res.status(401).json({
                success: false,
                message: '用户名或密码不正确'
            });
        }
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message
        });
    }
};

// 获取用户信息
const getUserProfile = async (req, res) => {
    try {
        const user = await User.findById(req.user._id).select('-password');
        if (user) {
            res.json({
                success: true,
                data: {
                    userInfo: {
                        _id: user._id,
                        username: user.username,
                        nickname: user.nickname,
                        avatar: user.avatar,
                        phone: user.phone,
                        isOnline: user.isOnline,
                        lastLoginTime: user.lastLoginTime
                    }
                }
            });
        } else {
            res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

// 更新用户信息
const updateUserProfile = async (req, res) => {
    try {
        const user = await User.findById(req.user._id);
        if (user) {
            user.nickname = req.body.nickname || user.nickname;
            user.avatar = req.body.avatar || user.avatar;
            user.phone = req.body.phone || user.phone;

            const updatedUser = await user.save();
            res.json({
                success: true,
                data: {
                    userInfo: {
                        _id: updatedUser._id,
                        username: updatedUser.username,
                        nickname: updatedUser.nickname,
                        avatar: updatedUser.avatar,
                        phone: updatedUser.phone,
                        isOnline: updatedUser.isOnline,
                        lastLoginTime: updatedUser.lastLoginTime
                    }
                }
            });
        } else {
            res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message
        });
    }
};

// 用户退出登录
const logoutUser = async (req, res) => {
    try {
        const user = await User.findById(req.user._id);
        if (user) {
            user.isOnline = false;
            await user.save();
            res.json({
                success: true,
                data: {
                    message: '退出登录成功'
                }
            });
        } else {
            res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

module.exports = {
    registerUser,
    loginUser,
    getUserProfile,
    updateUserProfile,
    logoutUser
}; 